/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.etop.weibo.servlet;

import com.etop.weibo.util.WeiBoException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author jansing
 */
public class BaseServlet extends HttpServlet {

    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        try {
            Method m = this.getClass().getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            System.out.println(req.getRequestURI() + "?" + req.getQueryString());
            String path = (String) m.invoke(this, req, resp);
            String redirectPrefix = "redirect:";
            if (path.startsWith(redirectPrefix)) {
                resp.sendRedirect(path.substring(redirectPrefix.length(), path.length()));
            } else {
                req.getRequestDispatcher(path).forward(req, resp);
            }
        } catch (InvocationTargetException ex) {
            Throwable targetException = ex.getTargetException();
            if (targetException instanceof WeiBoException) {
                WeiBoException e = (WeiBoException) ex.getTargetException();
                req.setAttribute("err_msg", e.getMessage());
                req.getRequestDispatcher("/WEB-INF/error.jsp").forward(req, resp);
            }
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException ex) {
            Logger.getLogger(BaseServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}
